<template>
  <div>
    <div class="secondary-notification">
      <t-tabs v-model="params.readStatus" @change="tabChange">
        <t-tab-panel v-for="(tab, tabIndex) in TAB_LIST" destroy-on-hide :key="tabIndex" :value="tab.value" :label="$t(tab.label)" :lazy="true">
           <t-list v-if="msgData.totalRow > 0"
             class="secondary-msg-list"
             :async-loading="asyncLoading"
              style="max-height: 700px"
              @scroll="scrollHandler"
              @load-more="loadMore"
              :split="true">
            <t-list-item v-for="(item, index) in msgData.records" :key="index" @click="readNotice(item)">
              <p :class="['content']">
                  <TagDict :dictType='SYS_NOTICE_TYPE' :value='item.type'></TagDict>
                  {{ item.title }}
              </p>
              <template #action>
                <span class="msg-date">{{ dateFormatByMomentTimezone(item.createTime) }}</span>

                <div class="msg-action">
                  <t-tooltip
                    class="set-read-icon"
                    :overlay-style="{ margin: '6px' }"
                    :content="item.readStatus===0? '设为未读' : '设为已读'"
                  >
                    <span class="msg-action-icon" @click.stop="setReadStatus(item.id,item.readStatus==0?1:0)">
                      <t-icon v-if="item.readStatus===0" name="queue" size="16px" />
                      <t-icon v-else name="chat" />
                    </span>
                  </t-tooltip>
                </div>
              </template>
            </t-list-item>
          </t-list>
          <div v-else class="secondary-msg-list__empty-list">
            <empty-icon></empty-icon>
            <p>{{$t('notice.nothaveyet')}}</p>
          </div>
        </t-tab-panel>
      </t-tabs>
    </div>
    <t-dialog
      closeOnEscKeydown
      mode="full-screen"
      :footer="false"
      v-model:visible="visible"
      :header="tdialogContent.title"
    >
    <div style="text-align: center"><TagDict :dictType='SYS_NOTICE_TYPE' :value='tdialogContent.type' /></div>
    <div style="text-align: center"><Calendar1Icon /><span>{{ dateFormatByMomentTimezone(tdialogContent.createTime) }}</span></div>
    <div style="text-align: center" v-html="tdialogContent.content"></div>
    </t-dialog>
  </div>
</template>


<script setup lang="ts">
import { PageNoticeRes, UserNoticePageReq } from '@/api/system/notice/types';
import { computed, onMounted, ref } from 'vue';
import EmptyIcon from '@/assets/assets-empty.svg?component';
import { useNotificationStore } from '@/store';
import type { NotificationItem } from '@/types/interface';
import { ResultEnum } from '@/enums/httpEnum';
import { PageResponse } from '@/api/types';
import { SYS_NOTICE_TYPE } from '@/constants/dictTypes';
import { dateFormatByMomentTimezone } from '@/utils/date';
import {
  Calendar1Icon,
} from 'tdesign-icons-vue-next';
import i18n from '@/i18n';
import { ListProps } from 'tdesign-vue-next';
import { Reply } from '@noear/socket.d/transport/core/Entity';
import { Result } from '@/types/axios';
const TAB_LIST = [
  {
    label: 'userNotice.label.status.all',
    value: undefined,
  },
  {
    label: 'userNotice.label.status.1',
    value: 1,
  },
  {
    label: 'userNotice.label.status.0',
    value: 0,
  },
];
const asyncLoadingRadio = ref('load-more');
const asyncLoading = computed(() => {
  if (asyncLoadingRadio.value === 'loading-notData') {
    return ()=>i18n.global.t('common.notData');
  }
  return asyncLoadingRadio.value;
});

/**
 * 通知中心滚动事件
 */
 const scrollHandler: ListProps['onScroll'] = async (e) => {
  if(e.scrollBottom <= 1 ){
    if(asyncLoadingRadio.value == 'loading-notData'){
      return;
    }
    asyncLoadingRadio.value = 'loading';
    params.value.pageNumber=Number(params.value.pageNumber)+1;
    await requestNotice(false);
  }
}

/**
 * 通知中心点击加载更多事件
 */
 const loadMore: ListProps['onLoadMore'] = async () => {
    asyncLoadingRadio.value = 'loading';
    params.value.pageNumber=Number(params.value.pageNumber)+1;
    await requestNotice(false);
}

const msgData = ref<PageResponse<Array<PageNoticeRes>>>({
  records: [],
  pageNumber: 0,
  pageSize: 0,
  totalRow: 0
});

const tdialogContent = ref<PageNoticeRes>({
  title: '',
  id: '',
  type: 0,
  target: 0,
  content: '',
  status: 0,
  remark: '',
  userName: '',
  createTime: undefined,
  readStatus: 0
});

const params=ref<UserNoticePageReq>({
  pageNumber: 1,
  pageSize: 10,
  readStatus: undefined,
});

const tabValue = ref('msgData');

const visible = ref(false);
const selectedItem = ref<NotificationItem>();

const store = useNotificationStore();

const handleClickDeleteBtn = (item: NotificationItem) => {
  visible.value = true;
  selectedItem.value = item;
};

const tabChange = async (value: number)=>{
  params.value={
    pageNumber: 1,
    pageSize: 10,
    readStatus: value
  }
  await requestNotice(true);
}

/**
 * 设置通知读取状态
 */
const setReadStatus = async (noticeId:string,readStatus:number) => {
  if (readStatus === 0) {
    params.value.pageNumber=1
    params.value.pageSize=10
    let boolean = await store.readRef([noticeId],params.value);
    if(boolean){
      await requestNotice(true);
    }
  }else{
    params.value.pageNumber=1
    params.value.pageSize=10
    console.log('params',params)
    let boolean = await store.unreadRef([noticeId],params.value);
    if(boolean){
      await requestNotice(true);
    }
  }
};

/**
 * 读取通知
 */
const readNotice = async (item: PageNoticeRes) => {
  setTimeout(async () => {
    await setReadStatus(item.id,0);
  }, 1);
  
  tdialogContent.value = item;
  visible.value = true;
};



/**
 * 请求获取通知
 */
 const requestNotice = async (refresh:boolean)=>{
    try{
      let reply:Reply=await store.pageNotice(params.value);
      let res:Result<PageResponse<Array<PageNoticeRes>>>=JSON.parse(reply.dataAsString());
      if(ResultEnum.SUCCESS == res.code){
        if(res.result.records.length>0){
          params.value.pageNumber=res.result.pageNumber
          if(params.value.pageSize >= res.result.totalRow){
            asyncLoadingRadio.value = 'loading-notData'
          }else{
            asyncLoadingRadio.value = 'load-more';
          }
          if(refresh){
            msgData.value=res.result
          }else{
            res.result.records.forEach(item=>{
              msgData.value.records.push(item);
            })
            msgData.value.totalRow=res.result.totalRow
            msgData.value.pageNumber=res.result.pageNumber
            msgData.value.pageSize=res.result.pageSize
          }
        }else{
          asyncLoadingRadio.value = 'loading-notData'
        }
      }
    }catch(err){
      setTimeout(async () => {
        await requestNotice(true);
      }, 100);
      
    }
    
}

onMounted(async () => {
  await requestNotice(true);
});

</script>

<style lang="less" scoped>
@import url('./index.less');
</style>